//
//  IWCScanBarCodeViewController.h
//
//  Created by Placid on 2019/11/15.
//  Copyright © 2019 biu. All rights reserved.
//

#import "IWCScanBarCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

//设备宽/高/坐标
#define kDeviceWidth [UIScreen mainScreen].bounds.size.width
#define KDeviceHeight [UIScreen mainScreen].bounds.size.height
#define KDeviceFrame [UIScreen mainScreen].bounds

static const float kLineMinY = 185;
static const float kLineMaxY = 385;
static const float kReaderViewWidth = 200;
static const float kReaderViewHeight = 200;
static const float gap = 1;

@interface IWCScanBarCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *line;//交互线
@property (nonatomic, strong) NSTimer *lineTimer;//交互线控制
@property (nonatomic, strong) AVCaptureSession *qrSession;//回话
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *qrVideoPreviewLayer;//读取
@property (nonatomic, assign)BOOL isSuccess;//是否扫描成功
@property (nonatomic, assign) BOOL showError;
@property (nonatomic, assign) BOOL isSelected;
@end

@implementation IWCScanBarCodeViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  self.isSelected = NO;
  self.showError = NO;
  // Do any additional setup after loading the view from its nib.
  [self initUI];
  [self setOverlayPickerView];
  [self startQRCodeReading];
}
- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  if (self.showError){
    self.showError = NO;
    UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"无访问摄像头权限" preferredStyle: UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
  }
}
- (void)viewWillDisappear:(BOOL)animated
{
  [super viewWillDisappear:animated];
  if (!self.isSuccess) {
    [self cancleQRCodeReading];
  }
}
- (void)dealloc
{
  if (self.qrSession) {
    [self.qrSession stopRunning];
    self.qrSession = nil;
  }
  
  if (self.qrVideoPreviewLayer) {
    self.qrVideoPreviewLayer = nil;
  }
  
  if (self.line) {
    self.line = nil;
  }
  
  if (self.lineTimer)
  {
    [self.lineTimer invalidate];
    self.lineTimer = nil;
  }
}

#pragma mark - Target action

- (void)initUI
{
  self.title = @"二维码扫描";
  self.view.backgroundColor = [UIColor blackColor];
  
  AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  
  //摄像头判断
  NSError *error = nil;
  
  AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  
  if (error)
  {
    NSLog(@"无访问摄像头权限-%@", error.localizedDescription);
    
    self.showError = YES;
    
    return;
  }
  
  AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  [output setRectOfInterest:[self getReaderViewBoundsWithSize:CGSizeMake(kReaderViewWidth, kReaderViewHeight)]];
  
  AVCaptureSession *session = [[AVCaptureSession alloc] init];
  
  // 读取质量，质量越高，可读取小尺寸的二维码
  if ([session canSetSessionPreset:AVCaptureSessionPreset1920x1080])
  {
    [session setSessionPreset:AVCaptureSessionPreset1920x1080];
  }
  else if ([session canSetSessionPreset:AVCaptureSessionPreset1280x720])
  {
    [session setSessionPreset:AVCaptureSessionPreset1280x720];
  }
  else
  {
    [session setSessionPreset:AVCaptureSessionPresetPhoto];
  }
  
  if ([session canAddInput:input])
  {
    [session addInput:input];
  }
  
  if ([session canAddOutput:output])
  {
    [session addOutput:output];
  }
  
  //set output format,must after adding output into session
  [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
  
  //设置预览图层
  AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
  [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
  preview.frame = [UIScreen mainScreen].bounds;
  [self.view.layer insertSublayer:preview atIndex:0];
  
  self.qrVideoPreviewLayer = preview;
  self.qrSession = session;
}

- (CGRect)getReaderViewBoundsWithSize:(CGSize)asize
{
  return CGRectMake(kLineMinY / KDeviceHeight, ((kDeviceWidth - asize.width) / 2.0) / kDeviceWidth, asize.height / KDeviceHeight, asize.width / kDeviceWidth);
}

- (void)setOverlayPickerView
{
  //画中间的基准线
  self.line = [[UIImageView alloc] initWithFrame:CGRectMake((kDeviceWidth - 300) / 2.0, kLineMinY, 300, 12 * 300 / 320.0)];
  [self.line setImage:[UIImage imageNamed:@"line"]];
  [self.view addSubview:self.line];
  
  // 最上部view
  UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kLineMinY)];//80
  upView.alpha = 0.3;
  upView.backgroundColor = [UIColor colorWithRed:0.169 green:0.161 blue:0.141 alpha:1];
  [self.view addSubview:upView];
  
  // 用于处理电池条颜色的遮罩层
  UIView* coverView = [[UIView alloc]init];
  coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
  [self.view addSubview:coverView];
  if (@available(iOS 11.0, *)) {
    coverView.translatesAutoresizingMaskIntoConstraints = false;
    
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
                                              [coverView.bottomAnchor constraintEqualToAnchor:guide.topAnchor constant:0],
                                              [coverView.leftAnchor constraintEqualToAnchor:guide.leftAnchor constant:0],
                                              [coverView.rightAnchor constraintEqualToAnchor:guide.rightAnchor constant:0],
                                              [coverView.heightAnchor constraintEqualToConstant:100]
                                              ]];
  }
  
  // 手绘导航栏容器 View
  UIView* naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, kDeviceWidth, 44)];
  naviView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
  [self.view addSubview:naviView];
  
  if (@available(iOS 11.0, *)) {
    naviView.translatesAutoresizingMaskIntoConstraints = false;
    
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
                                              [naviView.topAnchor constraintEqualToAnchor:guide.topAnchor constant:0],
                                              [naviView.leftAnchor constraintEqualToAnchor:guide.leftAnchor constant:0],
                                              [naviView.rightAnchor constraintEqualToAnchor:guide.rightAnchor constant:0],
                                              [naviView.heightAnchor constraintEqualToConstant:44]
                                              ]];
  }
  
  // 导航栏标题
  UILabel* titleLabel = [[UILabel alloc] init];
  titleLabel.text = @"扫一扫";
  titleLabel.textColor = [UIColor whiteColor];
  titleLabel.translatesAutoresizingMaskIntoConstraints = false;
  [naviView addSubview:titleLabel];
  
  [NSLayoutConstraint activateConstraints:@[
                                            [titleLabel.centerXAnchor constraintEqualToAnchor:naviView.centerXAnchor],
                                            [titleLabel.centerYAnchor constraintEqualToAnchor:naviView.centerYAnchor],
                                            ]];
  
  // 导航栏返回按钮
  UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
  [btn setBackgroundColor:[UIColor clearColor]];
  [btn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal	];
  [btn addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside];
  [naviView addSubview:btn];
  
  // 导航栏相册按钮
  UIButton *albumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  [albumBtn setBackgroundColor:[UIColor clearColor]];
  [albumBtn setTitle:@"相册" forState:UIControlStateNormal];
  [albumBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  [albumBtn setFrame:CGRectMake(naviView.frame.size.width - 60, 11, 40, 20)];
  [albumBtn addTarget:self action:@selector(clickAlbum:) forControlEvents:UIControlEventTouchUpInside];
  [naviView addSubview:albumBtn];
  
  static const CGFloat btnGap = 10;
  static const CGFloat btnSize = 25;
  [btn.titleLabel setFont:[UIFont systemFontOfSize:25]];
  if (@available(iOS 11.0, *)) {
    btn.translatesAutoresizingMaskIntoConstraints = false;
    
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
                                              [btn.topAnchor constraintEqualToAnchor:guide.topAnchor constant:btnGap],
                                              [btn.leftAnchor constraintEqualToAnchor:guide.leftAnchor constant:btnGap],
                                              [btn.widthAnchor constraintEqualToConstant:btnSize],
                                              [btn.heightAnchor constraintEqualToConstant:btnSize]
                                              ]];
  } else {
    btn.frame = CGRectMake(gap, gap, btnSize, btnSize);
  }
  
  //左侧的view
  UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, kLineMinY, (kDeviceWidth - kReaderViewWidth) / 2.0, kReaderViewHeight)];
  leftView.alpha = 0.3;
  leftView.backgroundColor = [UIColor colorWithRed:0.169 green:0.161 blue:0.141 alpha:1];
  [self.view addSubview:leftView];
  
  //右侧的view
  UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(kDeviceWidth - CGRectGetMaxX(leftView.frame), kLineMinY, CGRectGetMaxX(leftView.frame), kReaderViewHeight)];
  rightView.alpha = 0.3;
  rightView.backgroundColor = [UIColor colorWithRed:0.169 green:0.161 blue:0.141 alpha:1];
  [self.view addSubview:rightView];
  
  CGFloat space_h = KDeviceHeight - kLineMaxY;
  
  //底部view
  UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, kLineMaxY, kDeviceWidth, space_h)];
  downView.alpha = 0.3;
  downView.backgroundColor = [UIColor colorWithRed:0.169 green:0.161 blue:0.141 alpha:1];
  [self.view addSubview:downView];
  
  //四个边角
  UIImage *cornerImage = [UIImage imageNamed:@"ScanQR1"];
  
  //左侧的view
  UIImageView *leftView_image = [[UIImageView alloc] initWithFrame:CGRectMake(
                                                                              CGRectGetMaxX(leftView.frame) + gap, // - cornerImage.size.width / 2.0,
                                                                              CGRectGetMaxY(upView.frame) + gap, // - cornerImage.size.height / 2.0,
                                                                              cornerImage.size.width,
                                                                              cornerImage.size.height
                                                                              )];
  leftView_image.image = cornerImage;
  [self.view addSubview:leftView_image];
  
  cornerImage = [UIImage imageNamed:@"ScanQR2"];
  
  //右侧的view
  UIImageView *rightView_image = [[UIImageView alloc] initWithFrame:CGRectMake(
                                                                               CGRectGetMinX(rightView.frame) - gap - cornerImage.size.width, // - cornerImage.size.width / 2.0,
                                                                               CGRectGetMaxY(upView.frame) + gap, // - cornerImage.size.height / 2.0,
                                                                               cornerImage.size.width,
                                                                               cornerImage.size.height
                                                                               )];
  rightView_image.image = cornerImage;
  [self.view addSubview:rightView_image];
  
  cornerImage = [UIImage imageNamed:@"ScanQR3"];
  
  //底部view
  UIImageView *downView_image = [[UIImageView alloc] initWithFrame:CGRectMake(
                                                                              CGRectGetMaxX(leftView.frame) + gap,// - cornerImage.size.width / 2.0,
                                                                              CGRectGetMinY(downView.frame) - gap - cornerImage.size.height + 1, //- cornerImage.size.height / 2.0,
                                                                              cornerImage.size.width,
                                                                              cornerImage.size.height
                                                                              )];
  downView_image.image = cornerImage;
  
  [self.view addSubview:downView_image];
  
  cornerImage = [UIImage imageNamed:@"ScanQR4"];
  
  UIImageView *downViewRight_image = [[UIImageView alloc] initWithFrame:CGRectMake(
                                                                                   CGRectGetMinX(rightView.frame) - gap - cornerImage.size.width,// - cornerImage.size.width / 2.0,
                                                                                   CGRectGetMinY(downView.frame) - gap - cornerImage.size.height + 1,// - cornerImage.size.height / 2.0,
                                                                                   cornerImage.size.width, cornerImage.size.height)];
  downViewRight_image.image = cornerImage;
  
  [self.view addSubview:downViewRight_image];
  
  //说明label
  UILabel *labIntroudction = [[UILabel alloc] init];
  labIntroudction.backgroundColor = [UIColor clearColor];
  labIntroudction.frame = CGRectMake(CGRectGetMaxX(leftView.frame), CGRectGetMinY(downView.frame) + 25, kReaderViewWidth, 20);
  labIntroudction.textAlignment = NSTextAlignmentCenter;
  labIntroudction.font = [UIFont boldSystemFontOfSize:13.0];
  labIntroudction.textColor = [UIColor whiteColor];
  labIntroudction.text = @"将二维码置于框内,即可自动扫描";
  [self.view addSubview:labIntroudction];
  
  // 底部 View 中添加手电筒图标
  UIButton *flashlightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  [flashlightBtn setBackgroundImage:[UIImage imageNamed:@"手电筒常态"] forState:UIControlStateNormal];
//  [flashlightBtn setBackgroundImage:[UIImage imageNamed:@"手电筒点击"] forState:UIControlStateSelected];
  [flashlightBtn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
  flashlightBtn .frame = CGRectMake(labIntroudction.center.x - 25, CGRectGetMinY(downView.frame) + 160, 50, 50);
  
  [self.view addSubview:flashlightBtn];
  
  CGFloat width = [UIScreen mainScreen].bounds.size.width - 2 * CGRectGetMaxX(leftView.frame) + 2;
  UIView *scanCropView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) - 1,kLineMinY,width, kReaderViewHeight + 2)];
  //  scanCropView.layer.borderColor = [UIColor greenColor].CGColor;
  //  scanCropView.layer.borderWidth = 2.0;
  [self.view addSubview:scanCropView];
}

#pragma mark -- 手电筒点击事件
-(void)onClick:(UIButton *)sender{
  
  Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
  if (captureDeviceClass !=nil) {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if ([device hasTorch] && [device hasFlash]){
      
      [device lockForConfiguration:nil];
      
      if (!self.isSelected) {

        device.torchMode = AVCaptureTorchModeOn;
        device.flashMode = AVCaptureFlashModeOn;
        self.isSelected = YES;
        [sender setBackgroundImage:[UIImage imageNamed:@"手电筒点击"] forState:UIControlStateNormal];
        
      } else {
          
        [device setTorchMode:AVCaptureTorchModeOff];
        [device setFlashMode:AVCaptureFlashModeOff];
        self.isSelected = NO;
        [sender setBackgroundImage:[UIImage imageNamed:@"手电筒常态"] forState:UIControlStateNormal];
      }
      [device unlockForConfiguration];
      }else{
        NSLog(@"初始化失败");
      }
    }else{
      NSLog(@"没有闪光设备");
  }
}

#pragma mark -- 点击相册按钮跳转选取相片
-(void)clickAlbum:(UIButton *)sender{
  UIImagePickerController *vc = [[UIImagePickerController alloc] init];
  vc.delegate = self;
  vc.allowsEditing = YES;
  vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark -- 实现 imagePicker 的代理事件
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  [picker dismissViewControllerAnimated:YES completion:nil];
  [self startQRCodeReading];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
  UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
  CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
  NSData *imageData = UIImagePNGRepresentation(image);
  CIImage *ciImage = [CIImage imageWithData:imageData];
  NSArray *features = [detector featuresInImage:ciImage];
  if(features.count > 0){
    CIQRCodeFeature *feature = [features objectAtIndex:0];
    NSString *scannedResult = feature.messageString;
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self handelStringValue:scannedResult];
  }else{
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self handelStringValue:@"err"];
  }
}
-(void)handelStringValue:(NSString *)result{
  if ([result isEqualToString:@"err"]) {
    UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"识别二维码失败" preferredStyle: UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    
    [self presentViewController:ac animated:YES completion:nil];
    [self startQRCodeReading];
  }else{
    self.IWCQRCodeSuccessBlock(self, result);
  }
  
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate 

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
  //扫描结果
  if (metadataObjects.count > 0)
  {
    [self stopQRCodeReading];
    
    AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
    
    if (obj.stringValue && ![obj.stringValue isEqualToString:@""] && obj.stringValue.length > 0)
    {
      NSLog(@"---------%@",obj.stringValue);
      self.isSuccess = YES;
      self.IWCQRCodeSuccessBlock(self, obj.stringValue);
    }
    else
    {
      if (self.IWCQRCodeFailBlock) {
        self.IWCQRCodeFailBlock(self);
        UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"識別二維碼失敗" preferredStyle: UIAlertControllerStyleAlert];
        [ac addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil]];
        
        [self presentViewController:ac animated:YES completion:nil];
      }
    }
  }
  else
  {
    if (self.IWCQRCodeFailBlock) {
      self.IWCQRCodeFailBlock(self);
    }
  }
}

#pragma mark 交互事件

- (void)onCancel
{
  [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)startQRCodeReading
{
  self.lineTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 20 target:self selector:@selector(animationLine) userInfo:nil repeats:YES];
  
  [self.qrSession startRunning];
  
  NSLog(@"start reading");
}

- (void)stopQRCodeReading
{
  if (self.lineTimer)
  {
    [self.lineTimer invalidate];
    self.lineTimer = nil;
  }
  
  [self.qrSession stopRunning];
  
  NSLog(@"stop reading");
}

//取消扫描
- (void)cancleQRCodeReading
{
  [self stopQRCodeReading];
  
  if (self.IWCQRCodeCancleBlock)
  {
    self.IWCQRCodeCancleBlock(self);
  }
  NSLog(@"cancle reading");
}

#pragma mark -
#pragma mark 上下滚动交互线

- (void)animationLine
{
  __block CGRect frame = self.line.frame;
  
  static BOOL flag = YES;
  
  if (flag)
  {
    frame.origin.y = kLineMinY;
    flag = NO;
    
    [UIView animateWithDuration:1.0 / 20 animations:^{
      
      frame.origin.y += 5;
      self.line.frame = frame;
      
    } completion:nil];
  }
  else
  {
    if (self.line.frame.origin.y >= kLineMinY)
    {
      if (self.line.frame.origin.y >= kLineMaxY - 12)
      {
        frame.origin.y = kLineMinY;
        self.line.frame = frame;
        
        flag = YES;
      }
      else
      {
        [UIView animateWithDuration:1.0 / 20 animations:^{
          
          frame.origin.y += 5;
          self.line.frame = frame;
          
        } completion:nil];
      }
    }
    else
    {
      flag = !flag;
    }
  }
  
}




@end
